<template>
  <div class="login-form">
    <el-form ref="form" :model="form" label-width="80px" :rules="phonerule">
      <el-form-item label="手机号" prop="userphone">
        <el-input v-model="form.userphone" type="tel" placeholder="请输入商家手机号"></el-input>
      </el-form-item>
      <el-form-item class="validCode" label="验证码" prop="validCode">
        <el-input class="validCode-input" v-model="form.validCode" type="text" placeholder="请输入验证码"></el-input>
        <el-button round class="validCodeSend" size="mini" type="success" @click="sendCode">发送验证码</el-button>
      </el-form-item>
      <el-form-item>
        <el-button class="login-btn" type="primary" @click="submitForm('form')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'LoginByUserPhone',
  data () {
    // 自定义校验规则
    var checkUserPhone = (rule, phone, callback) => {
      if (!phone) {
        return callback(new Error('手机号码不能为空'))
      }
      setTimeout(() => {
        if (!(/^[1][3,4,5,7,8][0-9]{9}$/).test(phone)) {
          callback(new Error('请输入合法的手机号码'))
        } else {
          // 向数据库查询用户名是否存在
          // this.$http.get('', {
          //   username: this.form.username
          // }).then(({data}) => {
          //   if (data === '1') {
          //     alert('账号登录')
          //   } else {
          callback()
          // }
          // })
        }
      }, 500)
    }
    var validateCode = (rule, code, callback) => {
      if (!code) {
        return callback(new Error('你还没有输入验证码呢'))
      }
      setTimeout(() => {
        if (!(/^\d{6}$/).test(code)) {
          callback(new Error('验证码填写不合法'))
        } else {
          callback()
        }
      }, 500)
    }
    return {
      form: {
        userphone: '',
        validCode: ''
      },
      phonerule: {
        userphone: [
          { validator: checkUserPhone, trigger: 'blur' }
        ],
        validCode: [
          { validator: validateCode, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    sendCode () {
      alert('发送成功')
    }
  }
}
</script>

<style lang="stylus" scoped>
  .login-form
    width: 350px
    box-sizing border-box
    .el-button
      margin-left: -20px
    .login-btn
      width: 100%
      margin-top 20px
    .validCode
      position: relative
      .validCode-input
        width: 160px
      .validCodeSend
        position: absolute
        right: 0
        top: 4px
        height: 30px
</style>
